<?php 

//if(!isset($_SESSION['sess_uid']) || (trim($_SESSION['sess_role']) == '')) {
session_start();
if (!isset($_SESSION['sess_uid'])){
	header("location: index.php");
	exit();
 } else
 
 {


require_once('db.php');

//Load Default Parameter :
$sql = "select * from tb_setting";
$setting  = @mysql_query($sql,$link);
$data	  = mysql_fetch_array($setting, MYSQL_ASSOC);


?>


<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <base href="" />
    <title>eTaxware : <?php echo $data['site_name']; ?></title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <script type="text/javascript">

</script>
	<link rel="shortcut icon" href="assets/images/icon.png" />
    <script type="text/javascript">if(parent.frames.length>0)top.location='process.php?module=pos'</script>
    <link rel="stylesheet" href="assets/css/bootstrap.css" type="text/css" charset="utf-8">
    <link rel="stylesheet" href="assets/css/posajax.css" type="text/css" charset="utf-8">
    <link rel="stylesheet" href="assets/css/non-responsive.css" type="text/css">
    <link rel="stylesheet" href="assets/css/print.css" type="text/css" media="print">
  
	<script src="assets/js/jquery-1.7.2.min.js"></script>
	<script type="text/javascript" src="assets/js/jquery.keyboard.min.js"></script> 	
	
    <script src="assets/js/purl.js"></script>
	
	<link href="assets/css/jquery.bxslider.css" rel="stylesheet" />  
	<script src="assets/js/jquery.bxslider.min.js"></script> 

	<script type="text/javascript" src="assets/js/bootstrap.js"></script> 
	<script type="text/javascript" src="assets/js/bootbox.js"></script>
	
	<script type="text/javascript" src="assets/js/jquery.autocomplete.js"></script>
	<link rel="stylesheet" href="assets/css/jquery.autocomplete.css" type="text/css" />
	
	<script type="text/javascript">
	$(document).ready(function(){
		$('.bxslider').bxSlider({minSlides:3,maxSlides:3,slideWidth:600,slideMargin:0,ticker:false,infiniteLoop:false,hideControlOnEnd:true,mode:'horizontal'});
		
	});
	</script> 
	
	
    <style>.btn-product { background: #FFFFFF; border:1px solid #FFFFFF; border-bottom: 0; }.btn-con .btn-default{ height: 42px; }</style>  	
	<style>.ui-keyboard { height: 0 !important; display: none !important; }</style>    


</head>
<body>
<div id="wrap">

<!-- Portal Top Nav Bar -->
<div class="navbar navbar-static-top navbar-inverse">
<div class="container">
	<!-- Portal Name -->
	<div class="navbar-header"><a class="navbar-brand">eTaxware : <?php echo $data['site_name']; ?></a></div>
	
	<!-- Portal Nav Menu -->
    <ul class="nav navbar-nav"></ul>    
  	<ul class="nav navbar-nav navbar-right">
		<li><a class="hov"> [ UserID : <?php echo $_SESSION["sess_name"] ?>, Role : <?php echo $_SESSION["sess_role"] ?> ]</a></li>		
		<li><a href="#" class="tip" data-placement="left" title="Load Pending Payments"><i class="glyphicon glyphicon-shopping-cart"></i></a></li>
		<li><a href="#" class="tip" data-placement="left" title="Current Sales Summary"><i class="glyphicon glyphicon-tasks"></i></a></li>
		<li><a href="logout.php" class="tip" data-placement="left" title="Logout.."><i class="glyphicon glyphicon-log-out"></i></a></li>
	</ul>
</div>
</div>
<!-- END OF Portal Top Nav Bar -->

<div class="container">
<div id="wrapper">
<div id="content">
<div class="c1">
<div class="pos">
<div id="pos">
    <form method="post" accept-charset="utf-8">
	
	<div style="display:none"><input type="hidden" name="session_id" value="" /></div>        
	
	<div class="well well-sm" id="leftdiv">              
    <div id="printhead">
        <h2><strong>eTaxware</strong></h2>
		<p><br></p>
		<p></p>
	</div>
	
	<div id="print">
        <table width="100%" border="0" cellpadding="0" cellspacing="0" class="table table-striped table-condensed table-hover miantable" style="margin:5px 0 0 0;">
			<thead>
			<tr class="success">
				<th style="width: 6%" class="satu">X</th>
				<th style="width: 58%">Product</th>		
				<th style="width: 7%">Qty</th>
				<th style="width: 24%">Price</th>
				<th style="width:19px; padding:0;">&nbsp;</th>
			</tr>
			</thead>	
        </table>
		
        <div id="prodiv">
			<div id="protbldiv" class="nano">
				<div class="content">
                    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="table table-striped table-condensed table-hover protable"  id="saletbl" style="margin:0;">
                        <tbody>
                        </tbody>
                    </table>
                </div>
				<div style="clear:both;"></div>
            </div>
        </div>
                     
        <div id="totaldiv">
			<table id="totaltbl" class="table table-striped table-condensed totals" style="margin-bottom:2px;">
				<tbody>
				<tr class="success">
					  <td width="25%">Total Items</td>
					  <td><span id="count">0</span></td>
					  <td width="25%">Total (A)</td>
					  <td class="text_right" colspan="2"><span id="total">0.00</span></td>
				</tr>
				<tr class="success">
					  <td width="25%">Discount (D) 
					  </td>
					  <td><span id="ds_con">0.00</span></td>
					  <td width="25%">S-Charge (B)                            </td>
					  <td class="text_right"><span id="cs_con">0.00</span></td>
				</tr>
				<tr class="success">
					  <td width="30%">
					  </td>
					  <td></td>
					  <td width="30%">Tax (C)                            </td>
					  <td class="text_right"><span id="ts_con">0.00</span></td>
					</tr>	
				<tr class="success">
					  <td colspan="2">Grand Total (A+B+C-D)</td>
					  <td class="text_right" colspan="2"><span id="total-payable">0.00</span></td>
				</tr>
				
				</tbody>
			</table>
        </div>
    </div>
	<!-- END OF PRINT DIV -->
	
	<div id="botbuttons" style="text-align:center;margin-bottom:0px;">
		<button type="button" class="btn btn-info" id="hold" style="width:123px;"><i class="glyphicon glyphicon-floppy-disk"></i>PENDING</button>
		<button type="button" class="btn btn-danger" id="cancel" style="width:123px;"><i class="glyphicon glyphicon-remove"></i>CANCEL</button>
		<button type="button" class="btn btn-success" id="payment" style="margin-right:0; width:123px;"><i class="glyphicon glyphicon-ok"></i>PAYMENT</button>
	</div>

	<!--default value from global setting-->
	<input type="hidden" name="customer" id="customer" value="3" />
	<input type="hidden" name="inv_tax" id="tax_val" value="<?php echo $data['def_tax'];?>" />
	<input type="hidden" name="inv_discount" id="discount_val" value="<?php echo $data['def_disc'];?>" />
	<input type="hidden" name="inv_scharge" id="scharge_val" value="<?php echo $data['def_scharge'];?>" />
	
	<input type="hidden" name="rpaidby" id="rpaidby" value="cash" style="display: none;" />
	<input type="hidden" name="count" id="total_item" value="" />
	
	<input type="hidden" name="hold_ref" id="hold_ref" value="" />
	<input type="hidden" name="paid_val" id="paid_val" value="" />
	<input type="hidden" name="cc_no_val" id="cc_no_val" value="" />
	<input type="hidden" name="cc_holder_val" id="cc_holder_val" value="" />
	
	<span id="hidesuspend"></span>
	<input type="submit" id="submit" value="Submit Sale" style="display: none;" />
    </div>
	<!-- END OF LEFTDIV -->
	</form>
 
	
	<div id="cp">		
	
		<ul class="bxslider">
			<?php	
			$sql 		= "select * from tb_category order by id asc";
			$result 	=  mysql_query($sql,$link);
			while($data_get=@mysql_fetch_array($result)){	
			?>
			<li><button type="button" class="btn btn-cat" value="<?php echo $data_get['id'];?>" id="category-<?php echo $data_get['id'];?>"><?php echo $data_get['cat_name'];?></button></li>
			<?php
			}
			?>
		</ul>
					
					
		<div id="lefttop">
		<form onsubmit="return false;" action="">
		<input name="code" id="CityAjax" class="form-control input-sm ac_input" placeholder="Cari Product ID" style="margin-bottom: 10px;" />
		<input name="s_result" id="s_result" class="form-control input-sm" placeholder="" readonly="readonly"  style="margin-bottom: 10px;" />
        </form>
		</div>
		
		<div class="btn-con">
		<button id="previous" type="button" class="btn  btn-info" style='z-index:10002;'>
		<i class="glyphicon glyphicon-chevron-left"></i>
		</button><button id="next" type="button" class="btn btn-info" style='z-index:10003;'>
		<i class="glyphicon glyphicon-chevron-right"></i></button>
		</div>
				
		<!-- Product Panel [button] -->	
		<div id="ajaxproducts">
			<div class="btn-product clearfix">
			<div id="proajax"></div>
			</div>	
		</div>
					
	</div>
</div> 
<!--END OF ID=POS -->
			  
<div style="clear:both;"></div>
</div>
<div style="clear:both;"></div>
</div>
</div>
<div style="clear:both;"></div>
</div>
</div>
</div>
</div>

<!-- Footer -->
<div id="footer">
    <div class="container">
	<p class="credit"> <a class="tip"><span id="cur-time"></span></a></p>  
	</div>
</div>

<!-- Loading Animation -->
<div id="loading" style="display: none;">
      <!--<div class="blackbg"></div>-->
      <div class="loader"><img src="assets/images/bx_loader.gif" alt="" /></div>
</div>
	
	

<!-- Payment Modal Form -->
<div class="modal fade" id="payModal" tabindex="-1" role="dialog" aria-labelledby="payModalLabel" aria-hidden="true">
      <div class="modal-dialog">
    <div class="modal-content">
          <div class="modal-header modal-primary">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove"></i></button>
        <h4 class="modal-title" id="payModalLabel">
              PAYMENT            </h4>
      </div>
          <div class="modal-body">
        <table class="table table-striped" style="margin-bottom:0;">
              <tbody>
            <tr>
                  <td width="50%">Customer</td>               
			<!--
				  <a href="#" class="btn btn-primary btn-xs showCModal"><i class="glyphicon glyphicon-plus-sign"></i>
                    Add Customer                    </a>
			-->		
					
                  <td width="50%"><span class="inv_cus_con">
                    <select id="_cust" class="form-control pcustomer" style="padding: 2px !important; height: auto !important;">
                    <?php
					$sql 		= "select * from tb_customer order by cust_id asc";
								$result =  mysql_query($sql,$link);
								while($data_get=@mysql_fetch_array($result)){	
												
					?>
					<option value="<?php echo $data_get['cust_id'];?>"><?php echo $data_get['cust_name'];?></option>
					<?php
								}
								
								
					
					?>
					</select>
                    </span></td>
                </tr>
			
			<tr>
                  <td>Total Items                </td>
                  <td><span style="background: #FFFF99; text-weight: bold; padding: 5px 10px; color: #000;"><span id="fcount"></span></span></td>
            </tr>


			
            <tr>
                  <td>Grand Total   </td>
                  <td><span style="background: #FFFF99; padding: 5px 10px; text-weight: bold; color: #000;"><span id="twt"></span></span></td>
            </tr>
           
            </tr>
            
          <td>Paid by              </td>
            <td><select name="paid_by" id="paid_by" class="form-control" style="padding: 2px !important; height: auto !important;">
                <option value="CASH">
                Cash                </option>
                <option value="CC">
                Credit Card                </option>
                <option value="DC">
                Debet Card                </option>
              </select></td>
          </tr><tr class="pcash">
            <td>Paid              </td>
            <td><input type="text" id="paid-amount" class="form-control"  style="padding: 2px !important; height: auto !important;" /></td>
          </tr>
              <tr class="pcash">
            <td>Return Change                  </td>
            <td><span style="background: #FFFF99; padding: 5px 10px; text-weight: bold; color: #000;" id="balance"></span></td>
          </tr>
          
		   <tr class="pcc" style="display:none;">
            <td>Card No                  </td>
            <td><input type="text" id="pcc" class="form-control"  style="padding: 2px !important; height: auto !important;" /></td>
          </tr>
		  
              <tr class="pcc" style="display:none;">
            <td>Card Holder                  </td>
            <td><input type="text" id="pcc_holder" class="form-control"  style="padding: 2px !important; height: auto !important;" /></td>
          </tr>
              
		<tr class="pcc" style="display:none;">
            <td>Issuer Bank                  </td>
            <td>
			<select name="issuer_bank" id="paid_by" class="form-control" style="padding: 2px !important; height: auto !important;">
			<?php
					$sql 		= "select * from tb_bank order by bank_id asc";
								$result =  mysql_query($sql,$link);
								while($data_get=@mysql_fetch_array($result)){	
												
			?>
					<option value="<?php echo $data_get['bank_id'];?>"><?php echo $data_get['bank_name'];?></option>
			<?php
								}
					
			?>
            </select>
			</td>
			  
          </tr>	  
			  
                </tbody>
              
            </table>
      </div>
          <div class="modal-footer">
		 
        <button type="button" class="btn btn-primary" data-dismiss="modal" style="margin-right:0; width:150px;">
            CANCEL            </button>
        <button class="btn btn-success" id="submit-sale" style="margin-right:0; width:150px;">
            BAYAR            </button>
      </div>
        </div>
  </div>
</div>
<!-- END OF Payment Modal Form -->	



<!-- Modal : Saved Order -->	
<div class="modal fade" id="susModal" tabindex="-1" role="dialog" aria-labelledby="susModalLabel" aria-hidden="true">
      <div class="modal-dialog">
    <div class="modal-content">
          <div class="modal-header modal-primary">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove"></i></button>
        <h4 class="modal-title" id="susModalLabel">
              Save Order            </h4>
      </div>
          <div class="modal-body">
        <table class="table table-striped" style="margin-bottom:0;">
              <tbody>
            <tr>
                  <td width="50%">Customer                <a href="#" class="btn btn-primary btn-xs showCModal"><i class="glyphicon glyphicon-plus-sign"></i>
                    Add Customer                    </a></td>
                  <td width="50%"><span class="inv_cus_con">
                    <select class="form-control pcustomer" style="padding: 2px !important; height: auto !important;">
                    <option value="3">Walk-in Client</option><option value="3">Table A</option><option value="3">Table B</option><option value="4">Member A</option><option value="5">Member B</option></select>
                    </span></td>
                </tr>
            
              <tr class="pcash">
            <td>Order Tags         :</td>
            <td><input type="text" name="hold_v" value="" class="form-control input-sm" id="hold_ref_v" /></td>
          
                </tbody>
              
            </table>
      </div>
          <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">
            Close            </button>
        <button class="btn btn-success" id="submit-hold">
            Submit            </button>
      </div>
        </div>
  </div>
</div>
<!----end of save order------->


<script type="text/javascript">
var KB = 0;
var DTIME = 1;
var count = 1;
var total = 0;
var an = 1;
var rt = 1;
var ids = new Array();
var p_page = 6;
var page = 0;
var cat_id = 1;
var sproduct_name;
var slast;
var total_cp = 0;
var next = 0;
var prev = 0;
var userid = '<?php echo $_SESSION['sess_uid'];?>';
var uid = '<?php echo $_SESSION['sess_id'];?>';

$(document).ready(function(){
	
	LoadFavourite();
	

	/*------------------------------Handling : Filter Numeric Only For Input Quantity----------*/
	var before_qty = 1;
	$(".nkb-input").live("focus",function(){before_qty=parseInt($(this).val())});
	$(".nkb-input").live("keypress",function(e){
		if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        bootbox.alert("Digits Only..!");
		$(this).val(before_qty);
		$(this).focus();
        return false;
	}
	})
	
	/*------------------------------Handling : Display Current Sales Summary----------*/
	$('a[title="Current Sales Summary"]').click(function(ev) {
		$('#loading').show();
		var d = new Date(); var curr_dt = d.getFullYear()+'/'+d.getMonth()+'/'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
		ev.preventDefault();
		var msg = '<table class="table table-striped" style="margin-bottom:0;"><tbody>';
		$.ajax({type:"GET",async:false,url:"process.php?module=pos&view=current_sales",
					data:{prodcat_status : 'F'},
					dataType:"html",
					success:function(data){
						$('#loading').hide();
						msg += data;
						//bootbox.alert('Data : '+data);
					}
		});
		msg += '</tbody></table>';
		bootbox.dialog({
				message: msg,
				title: "<h3>Current Total Sales</h3>"+'<h4>'+curr_dt+'</h4>',
				buttons: {
					success: {
					  label: "CLOSE"
					}
				}
				
		});
		return false;
	});
			

	/*------------------------------Function : Display Favourite Products----------*/
	function LoadFavourite(){
		var data = 1;
		$.ajax({type:"GET",async:false,url:"process.php?module=pos&view=getFavourite",
				data:{prodcat_status : 'F'},
				dataType:"html",
				success:function(data){
					cat_id=data;
				}
		});
		page = 0;
		$('#loading').show();	
		//alert('cat_id : ' +cat_id+' Data : '+data);
		$.ajax({
			type:"get",
			url:"process.php?module=pos&view=catalog",
			data:{category_id:cat_id,per_page:p_page},
			dataType:"html",
			success:function(data){
				$('#proajax').empty();
				var newPrs=$('<div></div>');
				newPrs.html(data);
				newPrs.appendTo("#proajax")
			}
		}).done(function(){
			$.ajax({
				type:"get",async:false,url:"process.php?module=pos&view=total_cp",data:{category_id:cat_id},dataType:"html",success:function(data){total_cp=data}
			}); 
			if (total_cp>0){page=1}else{page=0}
			$('#loading').hide();
			add_row();
		})	
	}
	
	
	/*------------------------------Function : Count Pagination Page----------*/
	function getPagination(count){
      paginationCount= Math.floor(count / p_page);
      paginationModCount= count % p_page;
      if((paginationModCount)!=0){
               paginationCount++;
      }
      return paginationCount;
	}
	
	/*------------------------------Handling : Next Button Of Products----------*/
	$('#next').click(function(){
		if (page<getPagination(total_cp)){
			next = page+1;
			$('#loading').show();
			$.ajax({type:"get",url:"process.php?module=pos&view=catalog",
			data:{category_id:cat_id,per_page:p_page,pageId:next},dataType:"html",success:function(data){$('#proajax').empty();var newPrs=$('<div></div>');newPrs.html(data);newPrs.appendTo("#proajax")}}
			).done(
				function(){
					page = next;
					prev = page-1;
					add_row();
					$('#loading').hide()
				}
			)
		}
		
	});
	
	/*------------------------------Handling : Prev Button Of Products----------*/
	$('#previous').click(function(){
		if (page>1){
				prev = page - 1;
				$('#loading').show();
								
				$.ajax({
					type:"get",url:"process.php?module=pos&view=catalog",
					data:{category_id:cat_id,per_page:p_page,pageId:prev},dataType:"html",success:function(data){$('#proajax').empty();var newPrs=$('<div></div>');newPrs.html(data);newPrs.appendTo("#proajax")}
				}).done(function(){
					page = prev;
					next = page+1;
					add_row();
					$('#loading').hide();	
				})
			}
	});
	
	
	/*------------------------------Handling : Display Product By Category----------*/
	$('button[id^="category-"]').click(function(){
			page = 0; 
			$('#loading').show();
			cat_id=$(this).val();
			$.ajax({
				type:"get",
				url:"process.php?module=pos&view=catalog",
				data:{category_id:cat_id,per_page:p_page},
				dataType:"html",
				success:function(data){
					$('#proajax').empty();
					var newPrs=$('<div></div>');
					newPrs.html(data);
					newPrs.appendTo("#proajax")
				}
			}).done(function(){
				$.ajax({
					type:"get",async:false,url:"process.php?module=pos&view=total_cp",data:{category_id:cat_id},dataType:"html",success:function(data){total_cp=data}
				}); 
				if (total_cp>0){page=1}else{page=0}
				$('#loading').hide();
				add_row();	
				
			})
	})
	
	
	/*------------------------------Function : Generate Payment/Order ID----------*/
	function GenerateID(code){
		var d = new Date();
		var c_d = d.getDate();
		var c_mo = d.getMonth();
		var c_y = d.getFullYear();
		var c_h = d.getHours();
		var c_mi = d.getMinutes();
		var c_s = d.getSeconds();
		var id = "";
		curr_datetime = c_y+'-'+c_mo+'-'+c_d+' '+c_h+':'+c_mi+':'+c_s;
		
		if (code=='BID'){
			id = 'B'+c_y+c_mo+c_d+c_h+c_mi+c_s+'-'+uid;
		} else 
		if (code=='OID') {
			id = 'O'+c_y+c_mo+c_d+c_h+c_mi+c_s+'-'+uid;
		}
		return id;
	}



	/*------------------------------Function : Build Payment JSON----------*/
	function BuildPaymentJson(){
		var items = [];
		var arrJson = {} ;
		var bill_id = GenerateID('BID');
		var order_id = GenerateID('OID');
		var cust = $("#_cust").find('option:selected').val();
		sale_items = $( "#saletbl" ).find('button[id^="del-"]');
		var i = 0;
		sale_items.each(function(index) {
			i = index+1;
			//console.log('i : '+i+' index : '+index);
			var prod_id = $( "#saletbl" ).find('input[id^="product-'+i+'"]').attr('id');
			var prod_nam= $( "#saletbl" ).find('input[name^="product'+i+'"]').attr('name');
			var len = prod_id.length-prod_nam.length-1;
			prod_id = prod_id.substr(prod_nam.length+1,len);
			var qty = $( "#saletbl" ).find('input[id^="quantity-'+i+'"]').val();
			//alert ('Len : '+len+' prod id : '+prod_id+' Prod Name : '+prod_nam+' qty : '+qty);
			//alert($(this).attr("id") +':' + $(this).attr("name") +':'+ $(this).val());
			//alert('prod_id : '+prod_id+' | prod_name : '+prod_nam+' | Qty : '+qty);
			var item = {
				"order_id" : order_id,
				"prod_id" : prod_id,
				"qty" : qty,
				"customer" : cust,
				"user_id" : userid,
				"status" : 'P',
				"bill_id" : bill_id,
				"order_tag" : ""
			};
			items.push(item); 
		})
		//alert(items[0].prod_id+' : '+items[0].qty);
		var paid = $("#paid-amount").val();
		var change = $("#balance").text();
		if (trim(paid)==''){paid="0.00";}
		if (trim(change)==''){change="0.00";}
		//build json for posting payment :
		ArrJson = {
		"bill" : {
			"bill_id"		:   bill_id,
			"tot_item"		:	$("#count").text(),
			"total"			:	$("#total").text(),
			"tax"			:	$("#ts_con").text(),
			"s_charge"		:   $("#s_charge").text(),
			"discount"		:	$("#ds_con").text(),
			"grand_tot"		:	$("#total-payable").text(),
			"paid"			:	paid,
			"change"		:	change,
			"paidby"		:	$("#paid_by option:selected").val(),
			"card_num"		:	$("#pcc").text(),
			"card_holder"	:	$("#pcc_holder").text(),
			"customer"		:	cust,
			"userid"		:	userid,
			//"datetime"		:   curr_datetime, no need db autoupdate
			"status"		:	'P',
			"reff_id"		:	''
			},
		"items" : items 	
		}
			//alert('bill no :'+ArrJson.bill.bill_id);
			/*		alert('Cust :'+ArrJson.bill.customer);
			alert('items :'+ArrJson.items[0].prod_id+' Qty : '+ArrJson.items[0].qty); */
		return ArrJson;
	}
	
	
	/*------------------------------Start Of Even Handling : Submit Payments----------*/		
	$('#submit').click(function(){
		var json2send = buildPaymentJson();
		console.log(JSON.stringify(json2send));
		$.ajax({
					type:"POST",
					async:false,
					//url:"process.php?module=pos&view=payment",
					url:"payment.php?sess_id=",
					data:{json: JSON.stringify(json2send)},
					dataType:"html",
					success: function (data, textStatus, jqXHR) {
						console.log('Sucess => data : '+data+' ,status : '+textStatus+' ,jqXHR : '+jqXHR);
						bootbox.alert('<em>Payment : '+textStatus+'</em>. Bill ID : '+data);
					},
					 error: function (xhRequest, ErrorText, thrownError) {
						bootbox.alert("Failed to process request correctly, please try again");
						console.log('xhRequest: ' + xhRequest + "\n");
						console.log('ErrorText: ' + ErrorText + "\n");
						console.log('thrownError: ' + thrownError + "\n");
					}
		})
	})
	
	
	/*------------------------------Start Of Even Handling : Delete Row----------*/		
	$("#saletbl").on("click",'button[class^="del_row"]',function(){
		var delID=$(this).attr('id');
		var dl_id=delID.split("-");
		var rw_no=dl_id[1];
		var p1=$('#price-'+rw_no);
		var q1=$('#quantity-'+rw_no);
		var row_price=parseFloat(p1.val()*q1.val());
		var row_quantity=parseInt(q1.val());
		
		total=total-row_price;
		current=parseFloat(total).toFixed(2);
		count=count-row_quantity;
		
		var ds=$('#discount_val').val();
				
		//handling with or without % for Discount.
		if(ds.indexOf("%")!==-1) {
			var pds=ds.split("%");
			var discount=(current*parseFloat(pds[0]))/100;
		}else{
			var discount=parseFloat(ds).toFixed(2);
		}
		
		//handling with or without % for Tax.
		var ts=$('#tax_val').val();
		if(ts.indexOf("%")!==-1) {
			var pts=ts.split("%");
			var tax=(current*parseFloat(pts[0]))/100;
		}else{
			var tax=parseFloat(ts).toFixed(2);
		}
		
		//handling with or without % for s_charge.
		var cs=$('#scharge_val').val();
		if(cs.indexOf("%")!==-1) {
			var pcs=cs.split("%");
			var s_charge=(current*parseFloat(pcs[0]))/100;
		}else{
			var s_charge=parseFloat(cs).toFixed(2);
		}
				
		var g_total	= current-discount+tax+s_charge;
	
		grand_total=parseFloat(g_total).toFixed(2);

		$('#cs_con').text(s_charge.toFixed(2));
		$("#ds_con").text(discount.toFixed(2));
		$('#ts_con').text(tax.toFixed(2));
		$("#total-payable").text(grand_total);
		$("#total").text(current);
		$("#count").text(count-1);
		an--;
		row_id=$("#row_"+rw_no);
		row_id.remove()
	});
	
	/*------------------------------Start Of Even Handling : Update Row----------*/	
	$("#update-row").click(function(){
		var rw=$('#rwNo').val();
		var op=parseFloat($('#price-'+rw).val());
		var oq=parseInt($('#quantity-'+rw).val());
		var np=parseFloat($('#nPrice').val());
		var nq=parseInt($('#nQuantity').val());
		var row_price=op;
		var row_quantity=oq;
		total=total-(op*oq);
		total=total+(np*nq);
		current=parseFloat(total).toFixed(2);
		count=count-oq;
		count=count+nq;
		
		var ds=$('#discount_val').val();
				
		//handling with or without % for Discount.
		if(ds.indexOf("%")!==-1) {
			var pds=ds.split("%");
			var discount=(current*parseFloat(pds[0]))/100;
		}else{
			var discount=parseFloat(ds).toFixed(2);
		}
		
		//handling with or without % for Tax.
		var ts=$('#tax_val').val();
		if(ts.indexOf("%")!==-1) {
			var pts=ts.split("%");
			var tax=(current*parseFloat(pts[0]))/100;
		}else{
			var tax=parseFloat(ts).toFixed(2);
		}
		
		//handling with or without % for s_charge.
		var cs=$('#scharge_val').val();
		if(cs.indexOf("%")!==-1) {
			var pcs=cs.split("%");
			var s_charge=(current*parseFloat(pcs[0]))/100;
		}else{
			var s_charge=parseFloat(cs).toFixed(2);
		}
		
		var g_total	= current-discount+tax+s_charge;

		
		grand_total=parseFloat(g_total).toFixed(2);
		
		$('#price-'+rw).val(np);
		$('#quantity-'+rw).val(nq);
		if($('#proModalLabel').text().length>13){
			pName=$('#proModalLabel').text().substring(0,13)+'..'
		}else{
			pName=$('#proModalLabel').text()
		}
		$("#total-payable").text(grand_total);
		$("#total").text(current);
		$("#count").text(count-1);
		$('#price_'+rw).text((np*nq).toFixed(2));
		$('#'+rw).text(pName+' @ '+np.toFixed(2));
		
		return false
	});
		
	
	
	/*------------------------------Start Of Even Handling : Quantity OnChange-----------*/	
	
	var before_qty,after_qty;
	$(".nkb-input").live("focus",function(){before_qty=parseInt($(this).val())});
	$(".nkb-input").live("change",function(e){
	
		after_qty=parseInt($(this).val());
		var row_id=$(this).attr('id');
		var sp_id=row_id.split("-");
		var id_no=sp_id[1];
		var p='#price-'+id_no;
		var p1='#price_'+id_no;
		var product_price=parseFloat($.trim($(p).val()));
		var row_price=parseFloat($.trim($(p1).text()));
		var gross_total=after_qty*product_price;
		gross_total=parseFloat(gross_total).toFixed(2);
		var b_count=(count-before_qty);
		var a_count=(b_count+after_qty);
		count=a_count;
		var b_total=(total-row_price);
		var a_total=(parseFloat(b_total)+parseFloat(gross_total));
		total=a_total;
		$(p1).empty();
		$(p1).append(gross_total);
		current=parseFloat(total).toFixed(2);
		
		var ds=$('#discount_val').val();
				
		//handling with or without % for Discount.
		if(ds.indexOf("%")!==-1) {
			var pds=ds.split("%");
			var discount=(current*parseFloat(pds[0]))/100;
		}else{
			var discount=parseFloat(ds).toFixed(2);
		}
		
		//handling with or without % for Tax.
		var ts=$('#tax_val').val();
		if(ts.indexOf("%")!==-1) {
			var pts=ts.split("%");
			var tax=(current*parseFloat(pts[0]))/100;
		}else{
			var tax=parseFloat(ts).toFixed(2);
		}
		
		//handling with or without % for s_charge.
		var cs=$('#scharge_val').val();
		if(cs.indexOf("%")!==-1) {
			var pcs=cs.split("%");
			var s_charge=(current*parseFloat(pcs[0]))/100;
		}else{
			var s_charge=parseFloat(cs).toFixed(2);
		}
				
		var g_total	= current-discount+tax+s_charge;
		
		grand_total=parseFloat(g_total).toFixed(2);

		$('#cs_con').text(s_charge.toFixed(2));
		$("#ds_con").text(discount.toFixed(2));
		$('#ts_con').text(tax.toFixed(2));
		
		$("#total-payable").text(grand_total);
		$("#total").text(current);
		
		$("#count").text(count-1);
	
	
	}) 
	
	/*------------------------------End Of Even Handling : Quantity OnChange-----------*/	
	
		
	/*------------------------------Handling : Keypress 13 on Document Prevent Def-----------*/		
/* 	$(document).bind('keypress',function(e){
		if(e.keyCode==13){
			e.preventDefault();
			return false
		}
	}); */
	
	/*------------------------------Handling : Function ADD_ROW---------------------------------*/	
	function add_row(){
		$('button[id^="product-"]').click(function(){
			if(count>=1000){
				bootbox.alert("Anda mencapai limit 999.");
				return false
			}
			if(an>=51){
				bootbox.alert("Anda sampai limit items! Silahkan lakukan payment dan buat bill baru untuk items berikutnya. Thank you!");
				$('#loading').hide();var divElement=document.getElementById('protbldiv');
				divElement.scrollTop=divElement.scrollHeight;
				return false
			}
			$('#loading').show();

			//append items on table 
			var v=$(this).val();
			item_price = parseFloat(v).toFixed(2);
			var leng=$(this).attr('id').length;
			var last=$(this).attr('id').substr(leng-4);
			var pric='price'+last;
			var quan='quantity'+last;
			var code='code'+last;
			var pr_name=$(this).attr('data-name');
			var prod_name=$.trim(pr_name);
			
			if(prod_name.length>16){
				pName=prod_name.substring(0,16)+'..'
			}else{
				pName=prod_name
			}
			var rcount=count;
			count=rt;
			var newTr=$('<tr id="row_'+count+last+'"></tr>');
			qty_c = count;
			newTr.html('<td class="satu" style="width: 9%;"><button class="del_row" id="del-'+count+last+'" value="'+item_price+'"><i class="glyphicon glyphicon-remove-circle"></i></button></td><td style="width: 53%;"><input type="hidden" class="code" name="product'+count+'" value="'+prod_name+'" id="product-'+count+last+'"><button type="button" class="btn btn-info btn-block btn-xs prod_name tip text-left" data-name="'+prod_name+'" id="'+count+last+'">&nbsp;&nbsp;'+pName+'-@'+item_price+'</button><span class="printspan">'+prod_name+'</span></td><td style="width: 12%; text-align:left;"><input class="keyboard nkb-input" name="quantity'+count+'" type="text" value="1" id="quantity-'+count+last+'" onclick="this.select();" autocomplete="off"></td><td style="width: 26%;" class="text-right"><input type="hidden" class="price" name="price'+count+'" value="'+item_price+'" id="price-'+count+last+'"><span id="price_'+count+last+'">'+item_price+'</span></td>');
			newTr.appendTo("#saletbl");
			//end of append items on table'
			
			//Total,Tax,Items#,Discount,S-Charge Calculation 
			total+=parseFloat(item_price);
			current=parseFloat(total).toFixed(2);
			
			var ds=$('#discount_val').val();
					
			//handling with or without % for Discount.
			if(ds.indexOf("%")!==-1) {
				var pds=ds.split("%");
				var discount=(current*parseFloat(pds[0]))/100;
			}else{
				var discount=parseFloat(ds).toFixed(2);
			}
			
			//handling with or without % for Tax.
			var ts=$('#tax_val').val();
			if(ts.indexOf("%")!==-1) {
				var pts=ts.split("%");
				var tax=(current*parseFloat(pts[0]))/100;
			}else{
				var tax=parseFloat(ts).toFixed(2);
			}
			
			//handling with or without % for s_charge.
			var cs=$('#scharge_val').val();
			if(cs.indexOf("%")!==-1) {
				var pcs=cs.split("%");
				var s_charge=(current*parseFloat(pcs[0]))/100;
			}else{
				var s_charge=parseFloat(cs).toFixed(2);
			}
					
			var g_total	= current-discount+tax+s_charge;
	
			grand_total=parseFloat(g_total).toFixed(2);
			count=rcount;
		
			$('#cs_con').text(s_charge.toFixed(2));
			$("#ds_con").text(discount.toFixed(2));
			$('#ts_con').text(tax.toFixed(2));
			$("#total-payable").text(grand_total);
			$("#total").text(current);
			
			$("#count").text(count);
			
			count++;rt++;
			an++;
	
			var divElement=document.getElementById('protbldiv');
			divElement.scrollTop=divElement.scrollHeight;
			$('#loading').hide()
			$('input[name^="quantity'+qty_c+'"]').focus();
				
			})
	} 
			
	
/*------------------------------Handling : Find Product / Scan Product Code---------------------------------*/	
	$('#scancode').keydown(function(e){
		
		if(e.keyCode==13){if(count>=1000){
			bootbox.alert("Anda mencapai Quantity Limit : 999.");
			return false
		}
		
		if(an>=51){
			bootbox.alert("Maximum Item! Silahkan lakukan payment dan buat payment untuk items selanjutnya. Terima Kasih!");
			$('#loading').hide();
			var divElement=document.getElementById('protbldiv');
			divElement.scrollTop=divElement.scrollHeight;
			return false
		}
		
		$('#loading').show();
			var v=$(this).val();
			$.ajax({
				type:"get",
				async:false,
				url:"process.php?module=pos&view=scan_product",
				data:{code:v},
				dataType:"json",
				success:function(data){
					if(data==null){
						bootbox.alert('Request Failed, Pastikan ID Product Benar dan Coba Lagi!');
						item_price=false
					}else{
						item_price=parseFloat(data.item_price).toFixed(2);
						sproduct_name=data.product_name;
						slast=data.last
					}
				},
				error:function(){
					bootbox.alert('Request Failed, Pastikan ID Product Benar dan Coba Lagi!');
					item_price=false
				}
			});
			
			if(item_price==false){
				$(this).val('');$('#loading').hide();
				return false
			}
			
			if(sproduct_name.length>13){
				pName=sproduct_name.substring(0,13)+'..'
			}else{
				pName=sproduct_name
			}
			
			var rcount=count;count=rt;
			var newTr=$('<tr id="row_'+count+slast+'"></tr>');
			newTr.html('<td class="satu" style="width: 9%;"><button class="del_row" id="del-'+count+slast+'" value="'+item_price+'"><i class="glyphicon glyphicon-remove-circle"></i></button></td><td style="width: 53%;"><input type="hidden" class="code" name="product'+count+'" value="'+sproduct_name+'" id="product-'+count+slast+'"><button type="button" class="btn btn-info btn-block btn-xs prod_name tip text-left" data-name="'+sproduct_name+'" id="'+count+slast+'">'+pName+' @ '+item_price+'</button><span class="printspan">'+sproduct_name+'</span></td><td style="width: 12%; text-align:center;"><input class="keyboard nkb-input" name="quantity'+count+'" type="text" value="1" id="quantity-'+count+slast+'" onclick="this.select();" autocomplete="off"></td><td style="width: 26%;" class="text-right"><input type="hidden" class="price" name="price'+count+'" value="'+item_price+'" id="price-'+count+slast+'"><span id="price_'+count+slast+'">'+item_price+'</span></td>');
			newTr.appendTo("#saletbl");
			total+=parseFloat(item_price);
			current=parseFloat(total).toFixed(2);
			var ds=$('#discount_val').val();
			
			if(ds.indexOf("%")!==-1){
				var pds=ds.split("%");
				var discount=(total*parseFloat(pds[0]))/100;
				var g_total=(total+parseFloat($('#ts_con').text()))-discount;
				$("#ds_con").text(discount.toFixed(2))
			}else{
				var g_total=(total+parseFloat($('#ts_con').text()))-parseFloat(ds);
				$("#ds_con").text(parseFloat(ds).toFixed(2))
			}
			
			var ts=$('#tax_val').val();
			if(ts.indexOf("%")!==-1){
				var pts=ts.split("%");
				var tax=(total*parseFloat(pts[0]))/100;
				var g_total=(total+tax)-parseFloat($('#ds_con').text());
				$("#ts_con").text(tax.toFixed(2))
			}else{
				var g_total=(total+parseFloat(ts))-parseFloat($('#ds_con').text());
				$("#ts_con").text(parseFloat(ts).toFixed(2))
			}
			
			grand_total=parseFloat(g_total).toFixed(2);
			count=rcount;$("#total-payable").text(grand_total);
			$("#total").text(current);
			$("#count").text(count);
			count++;
			rt++;
			an++;
			var divElement=document.getElementById('protbldiv');
			divElement.scrollTop=divElement.scrollHeight;
			$(this).val('');
			$('#loading').hide();
			e.preventDefault();
			return false}
	});
					
			
	/*------------------------------Handling : Payment Cancel---------------------------------*/		
	$("#cancel").click(function(){
		bootbox.confirm("Anda yakin membatalkan transaksi (jika ada) ?",
		function(result){
			if(result==true){
				$("#saletbl").empty();
				count=1,total=0,tax_value=0,an=1;
				$("#ds_con").text('0.00');
				$('#ts_con').text('0.00');
				$("#total-payable").text('0.00');
				$("#total").text('0.00');
				$("#count").text(count-1)
			}
		})
	}); 
	
	/*------------------------------Handling : Payment Click---------------------------------*/
	$("#payment").click(function(){
		$("#pay").empty();
		var g_total=(total+parseFloat($('#ts_con').text()))-parseFloat($('#ds_con').text());
		twt=parseFloat(g_total).toFixed(2);
		count=count-1;
		if(isNaN(twt)||twt=='0.00'){
			bootbox.alert('Tidak ada item yang dapat dibayar. Pilih Items !.');
			count=count+1;
			return false
		}
		twt=parseFloat(twt).toFixed(2);
		$('#twt').text(twt);
		$('#fcount').text(count);
		$('#is_delete').val('91');
		$('#payModal').modal();
		count=count+1;
		$('#total_item').val(count);
		$('.pcustomer').change(function(){
			$('#customer').val($(this).val())
		});
		$('#paid-amount').change(function(){
		$('#paid_val').val($(this).val())
		});
			
		$('#pcc').change(function(){$('#cc_no_val').val($(this).val())});
		$('#pcc_holder').change(function(){$('#cc_holder_val').val($(this).val())});
		$("#paid_by").change(function(){
			var p_val=$(this).val();
			$('#rpaidby').val(p_val);
			if(p_val=='CASH'){
				$('.pcc').hide();
				$('.pcash').show();
				$('input[id^="paid-amount"]').keydown(function(e){
					paid=$(this).val();
					if(e.keyCode==13){
						if(paid<total){
							bootbox.alert('Pembayaran kurang dari nilai bill');
							return false
						}
						$("#balance").empty();
						var balance=paid-twt;balance=parseFloat(balance).toFixed(2);$("#balance").append(balance);e.preventDefault();return false
					}
				})
			}else{
				$('.pcash').hide();
				$('.pcc').show();
				$('#pcc').focus();	
			}
			
		}); 

		/*------------------------------Handling : Payment Amount Change-----------------------------*/
	
		$("#payModal").on("change",'#paid-amount',function(){
				var paid=parseFloat($(this).val());
				if(paid<twt){
					bootbox.alert('Pembayaran lebih kecil dari Nilai BILL');
					$(this).val('');
					return false
				}
				$("#balance").empty();
					var balance=paid-twt;
					balance=parseFloat(balance).toFixed(2);
					$("#balance").append(balance)
		}) 
		
		$('#submit-sale').click(function(){$('#submit').trigger('click')})
	});
/*------------------------------end of payment Handling---------------------------------*/
	
/*----------Auto Complate Find Product By Code--------*/
	$("#CityAjax").autocomplete(
			"autocomplete.php",
			{
				delay:10,
				minChars:2,
				matchSubset:1,
				matchContains:1,
				cacheLength:10,
				select:selectItem,
				onFindValue:findValue,
				formatItem:formatItem,
				autoFill:true
			}
	);



	
});
/*------------------------------end of doc ready---------------------------------------*/

/*------------------------------Start of Utility Function---------------------------------------*/
if(DTIME){
		function sivamtime(){
			now=new Date();
			var month_names=new Array();
			month_names[month_names.length]="January";
			month_names[month_names.length]="February";
			month_names[month_names.length]="March";
			month_names[month_names.length]="April";
			month_names[month_names.length]="May";
			month_names[month_names.length]="June";
			month_names[month_names.length]="July";
			month_names[month_names.length]="August";
			month_names[month_names.length]="September";
			month_names[month_names.length]="October";
			month_names[month_names.length]="November";
			month_names[month_names.length]="December";
			
			var day_names=new Array();
			day_names[day_names.length]="Sunday";
			day_names[day_names.length]="Monday";
			day_names[day_names.length]="Tuesday";
			day_names[day_names.length]="Wednesday";
			day_names[day_names.length]="Thursday";
			day_names[day_names.length]="Friday";
			day_names[day_names.length]="Saturday";
			hour=now.getHours();
			min=now.getMinutes();
			sec=now.getSeconds();
			if(min<=9){min="0"+min}
			if(sec<=9){sec="0"+sec}
			if(hour>12){
				hour=hour-12;
				add="PM"
			}else{
				hour=hour;add="AM"
			}
			if(hour==12){
				add="PM"
			}
			time=day_names[now.getDay()]+", "+now.getDate()+" "+month_names[now.getMonth()]+" "+now.getFullYear()+", "+((hour<=9)?"0"+hour:hour)+":"+min+":"+sec+" "+add;
			
			if(document.getElementById){
				document.getElementById('cur-time').innerHTML=time
			}else if(document.layers){
				document.layers.theTime.document.write(time);
				document.layers.theTime.document.close()
			}
			setTimeout("sivamtime()",1000)
		}
		window.onload=sivamtime
}				


/*--------- strart of autocomplate ---------------------------*/
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
    chars = chars || "\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
    chars = chars || "\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function findValue(li) {
if( li == null ) return alert("No match!");

// if coming from an AJAX call, let's use the CityId as the value
if( !!li.extra ) var sValue = li.extra[0];

// otherwise, let's just display the value in the text box
else var sValue = li.selectValue;

//alert("The value you selected was: " + sValue);
}

function selectItem(li) {
	findValue(li);
}

function formatItem(row) {
	return row[0] + " " + row[1] ;
}

function lookupAjax(){
var oSuggest = $("#CityAjax")[0].autocompleter;
oSuggest.findValue();
return false;
}

function lookupLocal(){
	var oSuggest = $("#CityLocal")[0].autocompleter;

	oSuggest.findValue();

	return false;
}
		  
/*------------------------------end of utility Function---------------------------------------*/

</script>

<script type="text/javascript">

		  
</script>


</body>
</html>


<?php 

mysql_close($link);

} ?>